import PySimpleGUI as sg
import os
import numpy as np
import cv2
import PySimpleGUI as sg
import os
from PIL import Image, ImageTk
import io

def callback_function1():
    cap = cv2.VideoCapture(0)  # 从摄像头中取得视频

    # 获取视频播放界面长宽
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5)
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5)

    # 定义编码器 创建 VideoWriter 对象
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Be sure to use the lower case
    out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (width, height))

    while (cap.isOpened()):
        # 读取帧摄像头
        ret, frame = cap.read()
        if ret == True:
            # 输出当前帧
            out.write(frame)

            cv2.imshow('My Camera', frame)

            # 键盘按 Q 退出
            if (cv2.waitKey(1) & 0xFF) == ord('q'):
                cv2.imwrite("/home/c4isr/yolov5/testfiles/1.jpg", frame)
                cv2.imwrite("/home/c4isr/人脸识别项目/test.png", frame)
                break
        else:
            break

    out.release()
    cap.release()
    cv2.destroyAllWindows()
    sg.popup("您已经完成拍照！")
    print('您已经完成拍照！')

def callback_function2():
    # Get the folder containin:g the images from the user
    folder = '/home/c4isr/yolov5/runs/detect/exp'

    # PIL supported image types
    img_types = (".png", ".jpg", "jpeg", ".tiff", ".bmp")

    # get list of files in folder
    flist0 = os.listdir(folder)

    # create sub list of image files (no sub folders, no wrong file types)
    fnames = [f for f in flist0 if os.path.isfile(
        os.path.join(folder, f)) and f.lower().endswith(img_types)]

    num_files = len(fnames)  # number of iamges found
    if num_files == 0:
        sg.popup('No files in folder')
        raise SystemExit()

    del flist0  # no longer needed

    # ------------------------------------------------------------------------------
    # use PIL to read data of one image
    # ------------------------------------------------------------------------------

    def get_img_data(f, maxsize=(1200, 850), first=False):
        """Generate image data using PIL
        """
        img = Image.open(f)
        img.thumbnail(maxsize)
        if first:  # tkinter is inactive the first time
            bio = io.BytesIO()
            img.save(bio, format="PNG")
            del img
            return bio.getvalue()
        return ImageTk.PhotoImage(img)

    # ------------------------------------------------------------------------------

    # make these 2 elements outside the layout as we want to "update" them later
    # initialize to the first file in the list
    filename = os.path.join(folder, fnames[0])  # name of first file in list
    image_elem = sg.Image(data=get_img_data(filename, first=True))
    filename_display_elem = sg.Text(filename, size=(80, 3))
    file_num_display_elem = sg.Text('File 1 of {}'.format(num_files), size=(15, 1))

    # define layout, show and read the form
    col = [[filename_display_elem],
           [image_elem]]

    col_files = [[sg.Listbox(values=fnames, change_submits=True, size=(60, 30), key='listbox')],
                 [sg.Button('Next', size=(8, 2)), sg.Button('Prev', size=(8, 2)), file_num_display_elem]]

    layout = [[sg.Column(col_files), sg.Column(col)]]

    window = sg.Window('Image Browser', layout, return_keyboard_events=True,
                       location=(0, 0), use_default_focus=False)

    # loop reading the user input and displaying image, filename
    i = 0
    while True:
        # read the form
        event, values = window.read()
        print(event, values)
        # perform button and keyboard operations
        if event == sg.WIN_CLOSED:
            break
        elif event in ('Next', 'MouseWheel:Down', 'Down:40', 'Next:34'):
            i += 1
            if i >= num_files:
                i -= num_files
            filename = os.path.join(folder, fnames[i])
        elif event in ('Prev', 'MouseWheel:Up', 'Up:38', 'Prior:33'):
            i -= 1
            if i < 0:
                i = num_files + i
            filename = os.path.join(folder, fnames[i])
        elif event == 'listbox':  # something from the listbox
            f = values["listbox"][0]  # selected filename
            filename = os.path.join(folder, f)  # read this file
            i = fnames.index(f)  # update running index
        else:
            filename = os.path.join(folder, fnames[i])

        # update window with new image
        image_elem.update(data=get_img_data(filename, first=True))
        # update window with filename
        filename_display_elem.update(filename)
        # update page display
        file_num_display_elem.update('File {} of {}'.format(i + 1, num_files))

    window.close()

sg.change_look_and_feel("GreenMono")

layout = [
    [
        sg.Button("拍照", size=(10, 1)), sg.Text('           press q to capature')
    ],

    [sg.Image(filename='', key='-IMAGE-')],
    [
        sg.Text("请输入待检查人员图片所在的目录："),
        sg.In(size=(25, 1), enable_events=True, key="-FOLDER-"),
        sg.FolderBrowse('浏览'),
    ],  [
        sg.Text("待检查人员图片默认存放路径为", text_color="white", size=(20, 1)),
        sg.Text('/home/c4isr/yolov5/testfiles/', text_color="white", size=(40, 1))
    ],
    [   sg.Text(text_color="red", size=(23, 2), key="error"),
        sg.Button('开始检查', enable_events=True, key="检查"),
        sg.Text(text_color="red", size=(23, 2), key="error"),
    ], [
        sg.Text("                      准备检查军容风纪", size=(40, 1), key="-TOUT-", justification='center')
    ],
[   sg.Text(text_color="red", size=(22, 2), key="error"),
        sg.Button('查看结果图片', enable_events=True, key="查看"),
        sg.Text(text_color="red", size=(23, 2), key="error"),
    ]
]
window = sg.Window('军容风纪检查系统', layout, location=(800, 400))

while True:
    event, values = window.read()

    if event in (None,):
        break  # 相当于关闭界面

    elif event =="拍照" :
        callback_function1()




    elif event == "检查":
        if values["-FOLDER-"]:
            window["error"].update("")
            try:
                window["-TOUT-"].update("正在检查中...")
                os.system(' cd /home/c4isr/yolov5  && python detect-software.py  --source ./testfiles/1.jpg  --weights ./runs/train/exp3/weights/best.pt --conf 0.4')
                #os.system("gnome-terminal -e 'bash -c \"python /home/c4isr/yolov5/detect.py  --source /home/c4isr/yolov5/testfiles/1.jpg  --weights /home/c4isr/yolov5/runs/train/exp3/weights/best.pt --conf 0.4;exec bash\"")
                #os.system('bash && source activate pytorch17 && python /home/c4isr/yolov5/detect.py  --source /home/c4isr/yolov5/testfiles/1.jpg  --weights /home/c4isr/yolov5/runs/train/exp3/weights/best.pt --conf 0.4')
                #os.close('python /home/c4isr/yolov5/detect.py')
                #os.system("python /home/c4isr/yolov5/detect.py --source /home/c4isr/yolov5/testfiles/000058.jpg --weights /home/c4isr/yolov5/runs/train/exp3/weights/best.pt --conf 0.4")
                #window["-TOUT-"].update(msg)

                #window['progressbar'].UpdateBar(i)
                #os.system("%s")
                window["-TOUT-"].update('                      鉴定完毕！！！')
            except Exception as e:
                window["error"].update(str(e))


        else:
            sg.popup('请先输入待检查人员照片所在的路径！')

    elif event =="查看":
        callback_function2()

window.close()